package com.lkk.cg.util;

import com.lkk.cg.domain.Privilege;
import com.lkk.cg.domain.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.struts2.StrutsStatics;

import javax.servlet.ServletContext;
import java.util.List;

import static com.lkk.cg.util.PrivilegeUtils.getPrivilegeStringList;

/**
 * Created by lkk on 2014/12/6.
 */
public class AuthorizeInterceptor extends AbstractInterceptor {
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {

        //获得权限信息
        ServletContext sc = (ServletContext) (ActionContext.getContext().get(StrutsStatics.SERVLET_CONTEXT));
        List<Privilege> privilegesNeedLogin = (List<Privilege>) sc.getAttribute("privilegesNeedLogin");
        List<Privilege> privilegesNeedAuth = (List<Privilege>) sc.getAttribute("privilegesNeedAuth");
        List<String> urlsNeedLogin = getPrivilegeStringList(privilegesNeedLogin);
        List<String> urlsNeedAuth = getPrivilegeStringList(privilegesNeedAuth);

        //获得用户
        User user = (User) ActionContext.getContext().getSession().get("user");

        //获得请求的链接
        String name = invocation.getProxy().getActionName();
        String namespace = invocation.getProxy().getNamespace();
        String url = namespace + name;
        String privUrl = UrlUtils.formatUrl(url);

        //比较
        boolean needLogin = urlsNeedLogin.contains(privUrl);
        boolean needAuth = urlsNeedAuth.contains(privUrl);
        boolean hasLogin = user != null;
        boolean hasPrivilege = hasLogin && user.findPrivilegeByUrl(privUrl);

        if ((needLogin || needAuth) && !hasLogin) {
            addActionMessage(invocation);
            return "login";
        }
        if (needAuth && !hasPrivilege) {
            return "noPrivilege";
        }
        return invocation.invoke();
    }

    private void addActionMessage(ActionInvocation invocation) {
        Object action = invocation.getAction();
        if (action instanceof ValidationAware) {
            String msg = "您进行的操作需要登录才能进行...";
            ValidationAware vac = (ValidationAware) action;
            if (vac instanceof ActionSupport) {
                ActionSupport as = (ActionSupport) vac;
                msg = as.getText("authorize.nologin");
            }
            vac.addActionMessage(msg);
        }
    }

}
